import { h, Component } from 'preact';
import { connect } from 'preact-redux';
import DockBar from '~/components/DockBar';
import HeaderBar from '~/components/HeaderBar';
import ScrollLoading from '~/components/ScrollLoading';
import { Link } from 'preact-router/match';
import Loading from '~/components/Loading';
import { getMyWorks, modifyWorks, creatWorks, deleteWorks } from '~/api';
import { upImage } from '~/api/groups';
import validate, { VRequire, VPhone, VEmail } from '~/utils/validate';
import Modal from '~/components/Modal';
import classNames from 'classnames';
import s from './Works.scss';

class Works extends Component {

	constructor(props){
		super(props);
		this.state = {
			list: [],
			edit: false,
			cookId: this.props.user.id || null,
			editTitle: null,
			editId: null,
			editContent: null,
			editLogo: 'null',
			showModal: false,
			deletWorks: false,
			showError: false,
			message: null
		};
	}


	componentWillMount() {
		if (this.props.user.id) {
			this.getMyWorks(this.props.user.id);
		}
	}


	componentWillReceiveProps(nextProps) {
		if (nextProps.user !== this.props.user) {
			this.setState({
				cookId: nextProps.user.id
			});
			this.getMyWorks(nextProps.user.id);
		}
	}


	handleCloseModal = () => {
		this.setState({ showModal: false });
	}

	getMyWorks = (id) => {
		getMyWorks(id).then(res => {
			const data = res;
			this.setState({
				list: data
			});
		}).catch(error => {
			Loading.hide();
			this.showError(error.message || '网络异常！请重试');
		});
	}

	handleShowEdit = (id) => () => {
		console.log(this.state.editContent);
		if (id) {
			for (let i = 0; i < this.state.list.length; i += 1) {
				if (id === this.state.list[i].id) {
					this.setState({
						editTitle: this.state.list[i].title,
						editContent: this.state.list[i].content,
						editLogo: this.state.list[i].logo,
						editId: this.state.list[i].id,
						deletWorks: true,
						showModal: true
					});
				}
			}
		} else {
			console.log(this.state.editContent);
			this.setState({
				editTitle: null,
				editContent: null,
				editLogo: null,
				editId: null,
				deletWorks: false,
				showModal: true
			});
		}
	}

	handleValidate = () => {
		const {
			editTitle,
			editContent,
			editLogo
		} = this.state;
		return validate(
			VRequire(editLogo) ? '上传作品图片' : null,
			VRequire(editTitle) ? '请填写作品名称' : null,
			VRequire(editContent) ? '请填写作介绍' : null
		);
	}

	handleModify = () => {
		const {editTitle,
				editContent,
				editLogo,
				cookId,
				editId} = this.state;
		if (this.handleValidate()) {
			this.showError(this.handleValidate());
			return;
		}
		Loading.show();
		modifyWorks({
			title: editTitle,
			content: editContent,
			logo: editLogo,
			cookId,
			id: editId,
			"updateTime" : "2017-05-15T20:56:38+08:00",
			"createTime" : "2017-05-15T20:56:41+08:00"
		}).then((res) => {
			Loading.hide();
			console.log(res);
			this.getMyWorks(this.props.user.id);
			this.setState({
				showModal: false
			});
		}).catch(error => {
			Loading.hide();
			this.showError(error.message || '网络异常！请重试');
		});
	}

	handleSubmit = () => {
		const {editTitle,
				editContent,
				editLogo,
				cookId,
				editId} = this.state;
		if (this.handleValidate()) {
			this.showError(this.handleValidate());
			return;
		}
		Loading.show();
		console.log(3333, editLogo);
		creatWorks({
			title: editTitle,
			content: editContent,
			logo: this.state.editLogo,
			cookId,
			"updateTime" : "2017-05-15T20:56:38+08:00",
			"createTime" : "2017-05-15T20:56:41+08:00"
		}).then((res) => {
			Loading.hide();
			console.log(res);
			this.getMyWorks(this.props.user.id);
			this.setState({
				showModal: false
			});
		}).catch(error => {
			Loading.hide();
			this.showError(error.message || '网络异常！请重试');
		});
	}

	handleDelete = () => {
		const {editId} = this.state;
		Loading.show();
		deleteWorks(editId).then((res) => {
			Loading.hide();
			console.log(res);
			this.getMyWorks(this.props.user.id);
			this.setState({
				showModal: false
			});
		}).catch(error => {
			Loading.hide();
			this.showError(error.message || '网络异常！请重试');
		});
	}

	showError = (message) => {
		this.setState({
			message,
			showError: true
		});
	}

	handleUpImage = () => {
		window.wx.ready(
			() => {
				window.wx.chooseImage({
					count: 1, // 默认9
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success: (res) => {
						const localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
						window.wx.uploadImage({
							localId: localIds[0], // 需要上传的图片的本地ID，由chooseImage接口获得
							isShowProgressTips: 1, // 默认为1，显示进度提示
							success: (res) => {
								const serverId = res.serverId; // 返回图片的服务器端ID
								Loading.show();
								upImage({
									mediaId: serverId,
									isMaterial: 0
								}).then((data) => {
									this.setState({
										editLogo: data
									});
									Loading.hide();
								}).catch(err => {
									Loading.hide();
									this.showError(err.message ? err.message : '系统繁忙, 请稍后重试！');
								});
							}
						});
					}
				});
			}
		);
	}

	render() {
		const { list } = this.state;
		return (
			<div className={s.root}>
				<HeaderBar
					setTitle="编辑作品"
					goBack
				>
					<span className={classNames('icon-add', 'white', s.edite)} onClick={this.handleShowEdit()}/>
				</HeaderBar>
				<div className={s.listwarp}>
					<div
					>
						<ul className={`${s.list} nls`} >
							{
								list.map(item => (
									<li className="clearfix" key={item.id} onClick={this.handleShowEdit(item.id)}>
										<div className="w2-5 fl">
											<img src={item.logo?`${item.logo}?x-oss-process=image/resize,m_fill,h_200,w_200`:null} alt=""/>
										</div>
										<div className="w7-5">
											<h3 className="txt_cut font">{item.title}</h3>
											<p className="txt_cut gray font-small">{item.content}</p>
										</div>
									</li>
								))
							}
						</ul>
					</div>
				</div>
				<Modal
					contentLabel="ModalB"
					isOpen={this.state.showModal}
					onRequestClose={this.handleCloseModal}
					shouldCloseOnOverlayClick={true}
				>
					<div className={s.pic}>
						{ this.state.editLogo && this.state.editLogo.length > 0 ?
							<img src={this.state.editLogo?`${this.state.editLogo}?x-oss-process=image/resize,m_fill,h_200,w_200`: null} onClick={this.handleUpImage} />
							: <div onClick={this.handleUpImage}>
								<span className="icon-add" />
								<p>上传图片</p>
							</div>
						}

					</div>
					<ul className="nls pd1 clearfix">
						<li className="mgb1">
							<input type="text" value={this.state.editTitle} placeholder="作品名称" onChange={e => this.setState({editTitle: e.target.value})} />
						</li>
						<li className="mgb1">
							<textarea
								className={s.textarea}
								placeholder="作品介绍" cols="30" rows="5"
								value={this.state.editContent}
								onChange={ e => this.setState({editContent: e.target.value}) }
							/>
						</li>
						<li className="clearfix">
							{
								this.state.deletWorks ?
								<div>
									<div className="fl w4-8 btn" onClick={this.handleModify}>修改</div>
									<div className="fr w4-8 btnb" onClick={this.handleDelete}>删除</div>
								</div>
								:
								<div>
									<div className="fl w4-8 btn" onClick={this.handleSubmit}>创建</div>
									<div className="fr w4-8 btnb" onClick={this.handleCloseModal}>取消</div>
								</div>
							}
						</li>
					</ul>
				</Modal>
				<Modal
					contentLabel="Modal"
					isOpen={this.state.showError}
					onRequestClose={() => {this.setState({showError: false});}}
					shouldCloseOnOverlayClick={true}
				>
					<h3 className="al-c pdt3">{this.state.message}</h3>
				</Modal>
			</div>
		);
	}
}

function mapStateToProps(state) {
	return {
		user: state.user
	};
}

export default connect(mapStateToProps)(Works);
